// routes_handle/user.js
const database = require("../databaseConfig/index");
const bcrypt = require("bcryptjs");
const jx = require("../jwt");
const dayjs = require("dayjs");

// 工具函数封装数据库查询
function query(sql, params, conn = database) {
  return new Promise((resolve, reject) => {
    conn.query(sql, params, (err, results) => {
      if (err) reject(err);
      else resolve(results);
    });
  });
}

// 封装事务执行器
async function withTransaction(taskFn) {
  const conn = await new Promise((resolve, reject) => {
    database.getConnection((err, connection) => {
      if (err) return reject(err);
      resolve(connection);
    });
  });

  try {
    await query("START TRANSACTION", [], conn);
    const result = await taskFn(conn);
    await query("COMMIT", [], conn);
    conn.release();
    return result;
  } catch (error) {
    await query("ROLLBACK", [], conn);
    conn.release();
    throw error;
  }
}

// 微信手机号登录（模拟解密）
exports.wxLogin = async ({ code, encryptedData, iv }) => {
  const phone = "13800000000"; // 实际应用中请替换为调用微信接口获取手机号

  const findUserSQL = "SELECT * FROM user WHERE FPhone = ?";
  const users = await query(findUserSQL, [phone]);

  if (users.length > 0) {
    const user = users[0];
    const token = await jx.signJWT({ id: user.Fid, phone });
    return {
      token,
      userId: user.Fid,
      name: user.FName,
      avatar: user.FAvatarUrl,
      phone: user.FPhone,
      hasCompany: !!user.FCompanyId,
    };
  }

  // 使用事务创建新用户
  return withTransaction(async (conn) => {
    const defaultPwd = bcrypt.hashSync("123456", 10);
    const defaultName = "微信用户" + dayjs().format("YYYYMMDD");

    const insertSQL =
      "INSERT INTO user (FPhone, FPassword, FName, FCreateTime, FUpdateTime) VALUES (?, ?, ?, NOW(), NOW())";
    const result = await query(insertSQL, [phone, defaultPwd, defaultName], conn);
    const userId = result.insertId;
    const token = await jx.signJWT({ id: userId, phone });

    return {
      token,
      userId,
      name: defaultName,
      avatar: "",
      phone,
      hasCompany: false,
    };
  });
};

// 账号密码登录（如果用户不存在，则注册）
exports.login = async ({ phone, password }) => {
  if (!phone || !password) throw new Error("手机号和密码不能为空");

  const userSQL = "SELECT * FROM user WHERE FPhone = ?";
  const users = await query(userSQL, [phone]);

  if (users.length === 0) {
    // 注册新用户
    return withTransaction(async (conn) => {
      const hashPwd = bcrypt.hashSync(password, 10);
      const defaultName = "微信用户" + dayjs().format("YYYYMMDD");

      const insertSQL =
        "INSERT INTO user (FPhone, FPassword, FName, FCreateTime, FUpdateTime) VALUES (?, ?, ?, NOW(), NOW())";
      const result = await query(insertSQL, [phone, hashPwd, defaultName], conn);
      const userId = result.insertId;
      const token = await jx.signJWT({ id: userId, phone });

      return {
        token,
        userId,
        name: defaultName,
        avatar: "",
        phone,
        hasCompany: false,
      };
    });
  }

  const user = users[0];
  if (!bcrypt.compareSync(password, user.FPassword)) {
    const err = new Error("手机号或密码错误");
    err.status = 401;
    throw err;
  }

  const token = await jx.signJWT({ id: user.Fid, phone });
  return {
    token,
    userId: user.Fid,
    name: user.FName,
    avatar: user.FAvatarUrl,
    phone: user.FPhone,
    hasCompany: !!user.FCompanyId,
  };
};

// 获取用户信息
exports.getUserInfo = async (userId) => {
  const userSQL = `
    SELECT Fid AS userId, FName AS username, FAvatarUrl AS avatar, 
           FPhone AS phone, FCompanyId AS companyId 
    FROM user WHERE Fid = ?`;
  const users = await query(userSQL, [userId]);
  return users[0];
};

// 修改用户信息
exports.updateUserInfo = async ({ userId, name, avatar }) => {
  const updateSQL = `
    UPDATE user SET FName = ?, FAvatarUrl = ?, FUpdateTime = NOW() 
    WHERE Fid = ?`;
  await query(updateSQL, [name, avatar, userId]);
};
